'use strict';
const {
    dialog,
    BrowserWindow,
    remote
} = require('electron').remote;
var path = require('path');
var fs = require('fs');


let filepath = "";
let title = "";
let saved = true;

$(document).ready(function () {
    let text = $(".shadowText");
	let circle = $(".shadowCircle");
	text.css({'left':'30px'});
    circle.css({'left': '3px'});
    
    $('#noteAdd').click(function() {
		createNew();
    });
    
    $('#noteDirectoryAdd').click(function() {
		openNew();
    });

    $('#saveFile span').click(function() {
        if(saveFile()) {
            alert("保存成功");
        }
    });

    $('.quit').click(function () {
        if (require('electron').remote.getGlobal('sharedObject').shadowOn) {
            require('electron').remote.BrowserWindow.getFocusedWindow().close();
        } else {
            if (checkSaved()) {
                ipcRenderer.send('quit-program');
            }
        }
    });

    $('#titleInput').bind('input propertychange', function () {
        saved = false;
    });

    $('#contentInput').bind('input propertychange', function () {
        saved = false;
    });
});

//打开新笔记
function openNew() {
    if (checkSaved()) {
        let path = chooseFile()[0];
        if (path) {
            if (loadFile(path)) {
                filepath = path;
                saved = true;
            } else {
                alert("打开文件失败");
            }
        }
    }
}

//选择文件，返回path
function chooseFile() {
    return dialog.showOpenDialog(BrowserWindow.getFocusedWindow(), {
        filters: [{
            name: 'Recoder File',
            extensions: ['rml']
        }]
    });
}

//读取并加载文件，成功返回true，失败返回false
function loadFile(path) {

    //Todo: 检查文件合法性

    try {
        let filestring = fs.readFileSync(path.toString(), 'utf-8');
        let flag = praseFileString(filestring);
        return flag;
    } catch (err) {
        console.log(err);
        alert(err);
        return false;
    }
}

//解析文件内容并添加到文本框，成功返回true，失败返回false
function praseFileString(fileXML) {
    let parser = new DOMParser();
    console.log(fileXML);
    let xmlDoc = parser.parseFromString(fileXML, "text/xml");

    let title = xmlDoc.getElementsByTagName('title')[0].firstChild.nodeValue;
    let content = xmlDoc.getElementsByTagName('content')[0].firstChild.nodeValue;
    let picture = xmlDoc.getElementsByTagName('picture')[0].firstChild.nodeValue;

    //Todo:...

    if (title && content && picture) {
        $('#titleInput').val(title);
        $('#contentInput').html(toHtmlString(content));
        clearCanvas();
        loadCanvas(picture);
        //Todo:...
        return true;
    }
    return false;
}

//选择文件夹，文件名，返回path
function chooseFolder() {
    return dialog.showSaveDialog(BrowserWindow.getFocusedWindow(), {
        filters: [{
            name: 'Recoder File',
            extensions: ['rml']
        }],
        defaultPath: filepath ? filepath : $('#titleInput').val()
    });
}

//创建新的笔记
function createNew() {
    if (checkSaved()) {
        $('#titleInput').val("untitled");
        $('#contentInput').html("");
        filepath = "";
        saved = true;
    }
}

//保存文件，成功返回true，失败返回false
function saveFile() {
    if (!filepath) {
        filepath = chooseFolder();
        if (!filepath) {
            return false;
        }
    }

    try {
        fs.writeFileSync(filepath.toString(), buildFileString())
        console.log("save success");
        saved = true;
        return true;
    } catch (err) {
        console.log(err);
        return false;
    }
}

//根据页面构建储存文件
function buildFileString() {
    //header
    let filestring = "<?xml version='1.0' encoding='utf-8'?>";
    filestring += "<root>";
    //title
    filestring += "<title>" + toXmlString($('#titleInput').val()) + "</title>";
    //content
    filestring += "<content>" + toXmlString($('#contentInput').html()) + "</content>";
    //picture
    console.log(canvasToBase64());
    filestring += "<picture>" + toXmlString(canvasToBase64()) + "</picture>";
    //Todo: ...
    filestring += "</root>";
    return filestring;
}

function autoSave() {
    //Todo: 使用临时文件保存
}

//未保存提示，继续操作返回true，取消操作返回false
function checkSaved() {
    if (saved) {
        return true;
    }

    let filename = "";
    if (filepath) {
        let arr = filepath.split('\\');
        filename = arr[arr.length - 1];
    } else {
        filename = $('#titleInput').val();
    }
    switch (dialog.showMessageBox(BrowserWindow.getFocusedWindow(), {
        buttons: ["是", "否", "取消"],
        message: '是否保存更改到"' + filename + '"中?'
    })) {
        case 0:
            if (saveFile()) {
                return true;
            } else {
                return false;
            }
        case 1:
            return true;
        case 2:
            return false;
    }
}

function canvasToBase64() {
    return $('#painter')[0].toDataURL('image/png');
}

function loadCanvas(base64) {
    var img = new Image();
    img.src = base64;
    img.onload = function () {
        $('#painter')[0].getContext('2d').drawImage(img, 0, 0);
    };
    console.log("load success");
}

function toXmlString(str) {
    return str.replace(new RegExp("<", "gm"), "&lt;").replace(new RegExp(">", "gm"), "&gt;").replace(new RegExp("&", "gm"), "&amp;").replace(new RegExp("​", "gm"), "");
}

function toHtmlString(str) {
    return str.replace(new RegExp("&lt;", "gm"), "<").replace(new RegExp("&gt;", "gm"), ">").replace(new RegExp("&amp;", "gm"), "&");
}